﻿using UnityEngine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
//using System.Data;
//using System.Drawing;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;
//using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
[Serializable]
public class SocketClient {

    public string _serverIp;

    //定义接收服务端发送消息的回调
    public delegate void ReceiveMsgCallBack(TransMsg strMsg);

    public Action Dele_OnConnect;

    public ReceiveMsgCallBack ReceiveCallBack;

    //创建连接的Socket
    Socket socketSend;
    //创建接收客户端发送消息的线程
    Thread threadReceive;

    public bool IsConnected()
    {
        return socketSend.Connected;
    }

    /// <summary>
    /// 连接
    /// </summary>
    public void Connect(string set_ip,string endPoint_set)
    {
        try
        {
        socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress ip = IPAddress.Parse(set_ip);//ip地址创建 
        Debug.Log("尝试连接：" + set_ip);
        //socketSend.Connect(ip, Convert.ToInt32(endPoint_set));//指定IP端口号链接
        socketSend.BeginConnect(
            new IPEndPoint(IPAddress.Parse(set_ip), Convert.ToInt32(endPoint_set)),
            (x) => {
                if (!socketSend.Connected)
                {
                    Debug.Log("连接失败");
                    return;
                }

                //开启一个新的线程不停的接收服务器发送消息的线程
                threadReceive = new Thread(new ThreadStart(Receive));
                //设置为后台线程
                threadReceive.IsBackground = true;
                threadReceive.Start();
                Debug.Log(string.Format("连接完毕,当前占用端口:{0}", socketSend.LocalEndPoint));
                Dele_OnConnect?.Invoke();
            },
            socketSend);
        //开启一个新的线程不停的接收服务器发送消息的线程
        //threadReceive = new Thread(new ThreadStart(Receive));
        //    //设置为后台线程
        //    threadReceive.IsBackground = true;
        //    threadReceive.Start();
        //    Debug.Log("连接完毕, 当前占用端口:" + socketSend.LocalEndPoint);
        //Dele_OnConnect();采用异步连接调用
    }
    catch (Exception ex)
        {
            Debug.LogWarning("连接服务端出错:" + ex.ToString());
        }
    }

        /// <summary>
        /// 接口服务器发送的消息
        /// </summary>
        private void Receive()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[2048];
                    //实际接收到的字节数
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    else
                    {
                    buffer = buffer.Take(r).ToArray();
                    TransMsg msg = SocketTool.TransByte2Msg(buffer);
                    Debug.Log( "接收远程服务器:" + socketSend.RemoteEndPoint + "发送的消息:" + msg._msgType);
                    ReceiveCallBack?.Invoke(msg);
                     
                    }
                }
            }
            catch (Exception ex)
            {
            ReceiveCallBack?.Invoke(new TransMsg("error", ex.ToString()));
            }
        }

        /// <summary>
        /// 客户端给服务器发送消息
        /// </summary>
        //public void Send()
        //{
        //    try
        //    {
        //        string strMsg = "客户端给服务端说：你好";
        //        byte[] buffer = new byte[2048];
        //        buffer = Encoding.Default.GetBytes(strMsg);
        //        int receive = socketSend.Send(buffer);
        //    }
        //    catch (Exception ex)
        //    {
        //        Debug.Log("发送消息出错:" + ex.Message);
        //    }
        //}

        public void Send(string msgType,string msgData)
        {
            try
            {
            byte[] buffer = SocketTool.TransMsg2Byte(msgType,msgData);
            socketSend.Send(buffer);
            }
            catch (Exception ex)
            {
                Debug.Log("发送消息出错:" + ex.Message);
            }
        }

    /// <summary>
    /// 断开连接
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void CloseConnect()
    {
        //终止线程
        if (threadReceive != null)
        {
            threadReceive.Abort();
            threadReceive.Join();
        }
        //关闭socket
        //if(socketSend!=null&&socketSend.Connected)
        //    socketSend.Close();
        //安全关闭socket的方法，防止关闭时仍有占用造成报错
        if (socketSend == null)
            return;
        if (!socketSend.Connected)
            return;
        try
        {
            socketSend.Shutdown(SocketShutdown.Both);
        }
        catch
        {
        }

        try
        {
            socketSend.Close();
        }
        catch
        {
        }

    }
}
